package 二叉树.练习;
//平衡二叉树

import 二叉树.基础.TreeNode;

public class Text_4 {
    public boolean isBalanced(TreeNode root) {

        if(root == null){
            return true;
        }
        if(getHeight(root)>=0){
            return true;
        }
        return false;

    }

    //在求高度的时候，判断是否是平衡二叉树
//    判断平衡二叉树的条件，左树和右树的高度相差小于1
    public int getHeight(TreeNode root){
        if(root ==null){
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight  = getHeight(root.right);

        if(rightHeight>=0 && leftHeight>=0
                && Math.abs(rightHeight - leftHeight) <= 1){
            return Math.max(rightHeight,leftHeight)+1;//正常求高度
        }else {
            return -1;
        }
    }
}